package com.gjy.mybatis.plugin;

import com.gjy.mybatis.annotation.Masking;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-24 13:52:26
 */
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class ResultSetHandlerInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(ResultSetHandlerInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("数据脱敏: {}", invocation.getMethod());
        Object proceed = invocation.proceed();
        if (proceed instanceof Collection) {
            Collection<?> objects = (Collection<?>) proceed;
            List<Object> list = new ArrayList<>(objects.size());
            for (Object o : objects) {
                list.add(masking(o));
            }
            return list;
        } else {
            return masking(proceed);
        }
    }

    private Object masking(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Masking.class)) {
                try {
                    field.setAccessible(true);
                    field.set(o, "***");
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return o;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
